import wepy from 'wepy'

export default class extends wepy.mixin {
  data = {
    goods_id: 0,
    goods_info: {},
    // 收货地址
    addressInfo: null
  }

  methods = {
    // 预览图片
    previewImage (current) {
      const urls = this.goods_info.pics.map(item => {
        return item.pics_big
      })
      wepy.previewImage({
        urls,
        current
      })
    },
    // 选择收货地址
    async chooseAddress () {
      const res = await wepy.chooseAddress().catch(err => err)
      if (res.errMsg !== 'chooseAddress:ok') return wepy.baseToast('已取消选择地址')
      wepy.baseToast('已选择收货地址')
      this.addressInfo = res
      wepy.setStorageSync('address',res)
      this.$apply()
    },
    // 点击加入购物车
    addCarHandle (info) {
      // 获取到全局的cart的数据
      // console.log(this.$parent.globalData.cart)
      const {goods_id, goods_name, goods_price, goods_big_logo} = info
      this.$parent.addCart(goods_id, goods_name, goods_price, goods_big_logo)
    }
  }
  async getGoodsDetail () {
    const {data:res} = await wepy.get('/goods/detail',{
      goods_id: this.goods_id
    })
    if (res.meta.status !== 200) return wepy.baseToast()
    this.goods_info = res.message
    this.$apply()
  }
  onLoad (options) {
    this.goods_id = options.goods_id
    this.getGoodsDetail()
    this.addressInfo = wepy.getStorageSync('address') || null
  }
  computed = {
    // 收货地址
    addressStr () {
      if (this.addressInfo === null) return '请选择收货地址'
      const {provinceName, cityName, countyName, detailInfo} = this.addressInfo
      return provinceName + cityName + countyName + detailInfo
    },
    // 计算购物车数量
    CartLength () {
      return this.$parent.globalData.cart.length
    }
  }
}
